package com.export.thread;

import com.alibaba.fastjson.JSONObject;
import com.export.bean.model.EmailModel;
import com.export.service.Impl.DeviceKvHistoryRepository_UNITED;
import com.export.bean.DeviceKvHistoryModel;
import com.export.bean.model.ExportModel;
import com.export.bean.model.StateModel;
import com.export.config.Contansts;
import com.export.config.FileHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.util.*;


/**
 * Created by MeowParse on 2017/5/9.
 * 优耐特斯
 * 查询
 * 开启查询数据、导出线程
 * 开启压缩线程
 * 发送邮件
 */
@Component("MultiExportThread")
@Scope("prototype")
public class MultiExportThread_UNITED extends Thread{

    private DeviceKvHistoryRepository_UNITED deviceKvHistoryRepositoryUNITED;

    private ExportModel exportModel;
    private StateModel stateModel;
    private Jedis redis ;
    private static final Logger logger = LoggerFactory.getLogger(MultiExportThread_UNITED.class);

    private boolean flag = true;
    private boolean uploadFlag = true;
    private int threadNum = 0;
    private String email;

//    private static MultiExportThread  multiExportThread;

    public MultiExportThread_UNITED(StateModel stateModel, ExportModel exportModel,
                                    DeviceKvHistoryRepository_UNITED deviceKvHistoryRepositoryUNITED, Jedis redis){
        this.exportModel = exportModel;
        this.stateModel = stateModel;
        this.deviceKvHistoryRepositoryUNITED = deviceKvHistoryRepositoryUNITED;
        this.redis = redis;
    }

    @Override
    public void run()  {

        logger.info("/*****************Start exporting/开始导出(优耐特斯)*****************************/");

        String fileName = exportModel.getUserName();
        String counter = "united/"+FileHandle.getCounter(exportModel);
//        Queue<String> date = new LinkedList<String>();
        Queue<String> dateByHour = new LinkedList<String>();
        String fileds[] = Contansts.filedsDeviceJSONModel;
        LinkedHashMap map = Contansts.mapDevice;
        String stringDate = FileHandle.getStringDate();
//        String filePath = Contansts.zipPath+fileName+stringDate+"\\";
        String filePath = Contansts.zipPath+fileName+stringDate+"/";
        //创建文件夹
        FileHandle.createFile(Contansts.zipPath);
        FileHandle.createFile(filePath);
        try {
//            date = FileHandle.getDateRange(exportModel.getStart(),exportModel.getEnd());
            dateByHour = FileHandle.getDateRangeByHour(exportModel.getStart(),exportModel.getEnd());
        } catch (Exception e) {
            e.printStackTrace();
        }
//        threadNum = date.size();
        threadNum = dateByHour.size();
        logger.info("TableNum/所需查询表数量(优耐特斯):"+threadNum);
        email = exportModel.getEmail();
        while(dateByHour.size()>0){
            if(stateModel.getActNum().size() < Contansts.maxThreadNum){
                stateModel.addActNum();
//                String[] tableNames = date.poll();
                String tableName = dateByHour.poll();
//                String tableName = Contansts.tableName+"_"+tableNames[0];
//                List<DeviceKvHistoryModel> deviceKvHistoryModels = deviceKvHistoryRepositoryUNITED.findDeviceKvHistory(tableNames,exportModel.getDeviceId());
                List<DeviceKvHistoryModel> deviceKvHistoryModels = deviceKvHistoryRepositoryUNITED.findDeviceKvHistoryByHour(tableName,exportModel.getDeviceId());
                logger.info("Query Complete/查询完成(优耐特斯):"+tableName);
                Thread workThread = new ActionThread(deviceKvHistoryModels,
                                                     fileds,map,filePath,
                                                     fileName+"_"+tableName,stateModel);    //创建线程
                workThread.start();
            } else {
                logger.info("Waiting,"+dateByHour.size()+"threads were not executed");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        logger.info("The number of zip threads/压缩线程数量(优耐特斯):"+threadNum);

        while(flag){
            try {
                Thread.sleep(1000);
                if(stateModel.getState() == threadNum){
                    flag = false;
                    Thread packThread = new PackThread(fileName+stringDate,filePath,Contansts.zipPath,stateModel);    //创建线程
                    packThread.start();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        logger.info("Wait for upload to complete/等待上传完成(优耐特斯)");

        while(uploadFlag){
            try {
                Thread.sleep(1000);
                if(stateModel.getUploadstate() == 1){
                    uploadFlag = false;
                    String content = "设备"+exportModel.getDeviceId()+":"+exportModel.getStart()+"---"+exportModel.getEnd()+"的数据(优耐特斯)";

                    EmailModel emailModel= new EmailModel(email,stateModel.getAddress(),content,counter,Contansts.title_united);
                    String emailJSON = JSONObject.toJSONString(emailModel);

                    redis.lpush(Contansts.emailQueue,emailJSON);
                    logger.info("Send a message to email queue/已向邮件队列推送消息(优耐特斯)");

                    stateModel.reset();
                    logger.info("/******************Load the next export message/读取下一条导出信息(优耐特斯)*******************/");

                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
